<?php
/**
 * Comment
 *
 * Класс Comment осуществляет вывод на экран древовидных комментариев
 * @author Стребиж Артём <artyom1989@gmail.com>
 * @version 1.0
 */
class View_Comment{
	/**
	 * функция вывода на экран комментария, позволяет отдельно выделять комментарии автора
	 *
	 * @param array $arrCurComment - массив с комментарием для вывода на экран
	 * 'ID_user' - id юзера
	 * 'first_name' - его имя
	 * 'creation' - дата создания
	 * 'ID_comment' - id комментария
	 * 'text' - сам комментарий
	 * @param int $type - id сущности(статья, каталог ...)
	 * @param int $idEssence - id сущности( статья с id = 5)
	 */
  	public static function displayComment($arrCurComment, $type, $idEssence, $arrUserInfo, $isLinear = false, $pollFlag = true, $branchMinimizeLinkFlag = false, $branchMinimizeFlag = false, $idFolder = 0, $issetChildren = true, $url=""){
  		$objSession = User_Session::instance();
  		$isLoggedIn = $objSession->isLoggedIn();
  		if (!$objSession->isLoggedIn())
  			$isLinear = true;

		$idUser = $arrUserInfo['ID_user'];
		$authorMode = ($arrCurComment['ID_user'] == $idUser) ? true : false;
		$authorName = $arrCurComment['login'];
		if ($isLinear)
			$isLinear = 1;
		else $isLinear = 0;
		if ($pollFlag)
			$pollFlag = 1;
		else $pollFlag = 0;
		$commentText = '';
		$id = $type . '_' . $arrCurComment['ID_comment'];
		if ($authorMode)
			$commentText .= '<div class="author">';
		$commentText .= '<div class="comments_author">
		      <div class="rigt_rating_box">';
		if ($isLoggedIn and $pollFlag and !$arrCurComment['delete_flag'])
			$commentText .= View_Poll::showMark($arrCurComment['ID_comment'], 2, $arrCurComment['session_user_poll'], Poll::calculateMark($arrCurComment['marks_minus'], $arrCurComment['marks_plus']), $arrCurComment['marks_minus'], $arrCurComment['marks_plus'], true, 0, $idFolder);

		$commentText .= '</div>
		<a class="author_link" href="' . W_ABSPATH . 'user/' .  $authorName . '" >
			<img src="' . W_IMAGES . 'pictures/user/vs_';
		if (!empty($arrCurComment['pic_path'])){
			$commentText .= $arrCurComment['ID_user'] . '.' . $arrCurComment['pic_path'] . '?' . rand();
		}
		else $commentText .= 'default.gif';

			$commentText .= '" class="user"/>';
			$commentText .= '
				</a>';
			$commentText .= '<ul class="name_autor">
							    			<li>
							    				<a href="' . W_ABSPATH . 'user/' .  $authorName . '">' . $authorName . '
							    				</a>
							    			</li>
							    			<li>' . Service_Date::getCaseDateForUser($arrCurComment['creation']) . '
							    			</li>
							    			<li>
							    			<a href="'.$url.'#comment'.$arrCurComment['ID_comment'].'" style="background:none; color:#0089B5; padding-left:0px;">#</a>
							    			</li>';
			if (($authorMode || User_User::checkIfUser('admin', $idUser)) && !$arrCurComment['delete_flag']){
				if (User_User::checkIfUser('admin', $idUser) || (strtotime(date(Service_Date::gLocalTime2BD())) - strtotime(date($arrCurComment['creation']))) < 900){ // 15 минут
					$onClick = 'comment.editComment(\'' . $id . '\', ' . $idEssence . ', \'' . $type . '\', ' . $arrCurComment['ID_comment'] . ', ' . $arrCurComment['ID_first_root_comment'] . ', ' . $isLinear . ', ' . $pollFlag . ', ' . $idFolder . ');return false;';
					$commentText .= '<li style="padding-top: 18px;"><input type="image" class="editComment" value="Редактировать" name="editComment" onClick="' . $onClick . '" src="' . W_ABSPATH . 'content/images/button/edit_comment_button.gif"></input></li>';

				}
				if (!$arrCurComment['delete_flag']){
					$commentText .= '
												<li style="padding-top: 18px;"><input type="image" class="deleteComment" value="Удалить" name="deleteComment" onClick="comment.deleteComment('; if ($authorMode) $commentText .= '1'; elseif ($arrUserInfo['role'] == 2) $commentText .= '2'; $commentText .= ', ' . $arrCurComment['ID_comment'] . ', ' . $arrCurComment['ID_user'] . '); return false;" src="' . W_ABSPATH . 'content/images/button/delete_comment_button.gif"></input></li>
												<div class="forAjaxLoadDeleteComment"></div>';
				}
			}
			$commentText .= '</ul>
					    	  </div>';

			$class = "";
			if ($arrCurComment['delete_flag'] == 1)
				$commentText .= '<p class="comment_text delete_modetator wysiwyg-content">' . $arrCurComment['text'] . '</p>';
		  $commentText .= '<div class="comment_text wysiwyg-content">' . $arrCurComment['text'] . '</div>';

		  	if ($arrCurComment['delete_flag'] != 1 && $isLoggedIn){
		  		$commentText .= '<ul class="link_comment">';
		  		$commentText .= '<a href="'.$url.'#comment'.$arrCurComment['ID_comment'].'" class="commentLink"></a>';
		  		if (!$isLinear){
		  			$url = W_ABSPATH . 'content/pages/comment/addComment.php?curEssenceId=' . $idEssence . '&type=' . $type . '&root=' . $arrCurComment['ID_comment'] . '&first_root=' . $arrCurComment['ID_first_root_comment'];
		  			$onClick = 'comment.showFormForAnswer(\'' . $id . '\', ' . $idEssence . ', \'' . $type . '\', ' . $arrCurComment['ID_comment'] . ', ' . $arrCurComment['ID_first_root_comment'] . ', ' . $isLinear . ', ' . $pollFlag . ', ' . $idFolder . ');return false;';
			 		$commentText .= '<li>
			 				<a attrIdanswerLink="' . $id . '" href="' . $url . '" class="answerLink" onClick="' . $onClick . '">Прокомментировать
			 				</a>
			  			  </li>';
			 		if ($branchMinimizeLinkFlag){ // свернуть/развернуть ветку комментариев
			 			if ($branchMinimizeFlag){
			 				$attr = ' minimized="yes" onClick="branchMaximize(this); return false;" ';
			 				$text = 'Развернуть ветку';
			 			}
			 			else {
			 				$attr = ' minimized="no"  onClick="branchMinimize(this); return false;" ';
			 				$text = 'Cвернуть ветку';
			 			}
			 			$commentText .= '<li><a href="" class="branchMinimizeLink" attr_id_root="' . $arrCurComment['ID_comment'] . '"' . $attr . ' style="' . ($issetChildren ? NULL : 'display:none;') . '" >' . $text . '</a></li>';
			 		}

			  	$commentText .= '</ul>';
		  		}
			  	else {
			 		if ($branchMinimizeLinkFlag){ // свернуть/развернуть ветку комментариев
			 			if ($branchMinimizeFlag){
			 				$attr = ' minimized="yes" onClick="branchMaximize(this); return false;" ';
			 				$text = 'Развернуть ветку';
			 			}
			 			else {
			 				$attr = ' minimized="no"  onClick="branchMinimize(this); return false;" ';
			 				$text = 'Cвернуть ветку';
			 			}
		  			$commentText .= '<li><a href="" class="branchMinimizeLink" attr_id_root="' . $arrCurComment['ID_comment'] . '"' . $attr . ' style="' . ($issetChildren ? NULL : 'display:none;') . '" >' . $text . '</a></li>';
			 		}
/*			 			if ($authorMode || $arrUserInfo['role'] == 2){
			  		$commentText .= '
							<li><input type="image" class="deleteComment" value="Удалить" name="deleteComment" onClick="comment.deleteComment('; if ($authorMode) $commentText .= '1'; elseif ($arrUserInfo['role'] == 2) $commentText .= '2'; $commentText .= ', ' . $arrCurComment['ID_comment'] . ', ' . $arrCurComment['ID_user'] . '); return false;" src="' . W_ABSPATH . 'content/images/icons/delete.gif"></input></li>
							<div class="forAjaxLoadDeleteComment"></div>';
			 			}		*/
			  		$commentText .= '</ul>';
			  	}
		  	}
		  	else {
			 		if ($branchMinimizeLinkFlag){ // свернуть/развернуть ветку комментариев
			 			if ($branchMinimizeFlag){
			 				$attr = ' minimized="yes" onClick="branchMaximize(this); return false;" ';
			 				$text = 'Развернуть ветку';
			 			}
			 			else {
			 				$attr = ' minimized="no"  onClick="branchMinimize(this); return false;" ';
			 				$text = 'Cвернуть ветку';
			 			}
						$commentText .= '<ul class="link_comment"><li><a href="" class="branchMinimizeLink" attr_id_root="' . $arrCurComment['ID_comment'] . '"' . $attr . ' style="' . ($issetChildren ? NULL : 'display:none;') . '" >' . $text . '</a></li></ul>';
			 		}
		  	}
		  	$commentText .= '<div id="' . $id . '" attrOpen="no"></div>'; // div для формы ответа
		  	if ($authorMode)
		  		$commentText .= '</div>';
		 return $commentText;
	}

	/**
	 * функция, вызываемая для вывода на экран всех переданных комментариев
	 *
	 * @param array $arrComments - комментарии
	 * 'ID_user' - id юзера
	 * 'first_name' - его имя
	 * 'creation' - дата создания
	 * 'ID_comment' - id комментария
	 * 'text' - сам комментарий
	 * @param int $idEssence - id сущности( статья с id = 5)
	 * @param int $type - id сущности(статья, каталог ...)
	 */
	public static function viewCurComments($arrComments, $idEssence, $type, $arrUserInfo, $isLinear = false, $pollFlag = true, $branchMinimizeFlag = false, $commentText = '', $idFolder = 0, $isRootParent = false, $arrForAnswer = array(), $url=""){
		$arrSize = sizeof($arrComments);
		if ($arrSize > 0){
	  	for ($i = 0; $i < $arrSize; $i++) {
	  		$commentText .= '<a name="comment' . $arrComments[$i]['ID_comment'] . '"></a>';
	  		$isRoot = ($arrComments[$i]['ID_comment'] == $arrComments[$i]['ID_first_root_comment']);
	  		($isRoot) ? $attrRoot = ' attrRoot="' . $arrComments[$i]['ID_comment'] . '"' : $attrRoot = '';
	  		$branchMinimizeLinkFlag = $isRoot;
	  		$style = '';
	  		if (!$isRoot && $isRootParent && $branchMinimizeFlag)
	  			$style = ' style="display: none;" ';
	    	$commentText .= '<div class="comment" attrId="' . $type . '_' . $arrComments[$i]['ID_comment'] . '"' . $attrRoot . $style . ' >';
	    	if($type == 'question' and $isRoot){
	    		$commentText .= View_Answer::displayAnswer($arrComments[$i], $arrForAnswer['idBestAnswer'], $arrForAnswer['questionAuthorId'], $arrForAnswer['isUserAdmin'], $idFolder, false, true, $branchMinimizeLinkFlag, $branchMinimizeFlag, isset($arrComments[$i]['children']), $type, $idEssence, $arrComments[$i]['rating'], $url);
	    	}else {

		    $commentText .= '<div commentId="'.$arrComments[$i]['ID_comment'].'" class="text_comment ';
		    $commentText .= ($arrComments[$i]['ID_user'] != $arrUserInfo['ID_user'] && ($arrComments[$i]['impress_time'] == null || ($arrComments[$i]['impress_time'] && $arrComments[$i]['impress_time'] < $arrComments[$i]['creation'])) ? ('newForUser') : (null));
		    $commentText .= '">';
				$commentText .= View_Comment::displayComment($arrComments[$i], $type, $idEssence, $arrUserInfo, $isLinear, $pollFlag, $branchMinimizeLinkFlag, $branchMinimizeFlag, $idFolder, isset($arrComments[$i]['children']),  $url);
				$commentText .= '</div>';
	    	}
			if(isset($arrComments[$i]['children']))
				$commentText .= View_Comment::viewCurComments($arrComments[$i]['children'], $idEssence, $type, $arrUserInfo, $isLinear, $pollFlag, $branchMinimizeFlag, '', $idFolder, $isRoot, $arrForAnswer, $url);
			$commentText .=  '</div>';
		}
		}
		else {
			$commentText .= '<script type="text/javascript">
												$(document).ready(function(){
													$("a[@attrIdanswerLink=\'' . $type . '_' . $idEssence . '_root' . '\']").click();
												});
											</script>';
		}
		return $commentText;
	}

	/**
	 * функция, вызываемая для вывода на экран всех переданных комментариев
	 *
	 * @param array $arrComments - комментарии
	 * 'ID_user' - id юзера
	 * 'first_name' - его имя
	 * 'creation' - дата создания
	 * 'ID_comment' - id комментария
	 * 'text' - сам комментарий
	 * @param int $idEssence - id сущности( статья с id = 5)
	 * @param int $type - id сущности(статья, каталог ...)
	 */
	public static function viewComments($arrComments, $idEssence, $type, $arrUserInfo, $isLinear = false, $hideAtStart = false, $viewLinkToAddRootComment = false, $textLink = '', $pollFlag = true, $idFolder = 0, $arrForAnswer = array(), $url=""){
/*							echo '<pre>';
			print_r($arrComments);
			echo '</pre>';*/

		$hideAtStart ? $style = 'style="display:none;"' : $style = '';
		if ($isLinear)
			$isLinear = 1;
		else $isLinear = 0;
		$hideAtStart ? $onClick = 'showCommentsBlock(' . $idEssence . '); return false;' : $onClick = 'closeCommentsBlock(' . $idEssence . '); return false;';
		if (isset($arrComments[0]['minimizeAllCommentsBranch']) && $arrComments[0]['minimizeAllCommentsBranch'] == 1)
			$branchMinimizeFlag = true;
		else $branchMinimizeFlag = false;
		$branchText = $type == "questio" ? 'комментарии к ответам' : 'ветки'; // пока написано неправильно специально ( нужно в js также сделать)
		if ($branchMinimizeFlag){
			$branchMinimizeAllCommentText = 'Развернуть все ' . $branchText;
			$onClickBranch = ' onclick="maximizeAllCommentsBranch(this); return false;" ';
		}
		else {
			$branchMinimizeAllCommentText = 'Cвернуть все ' . $branchText;
			$onClickBranch = ' onclick="minimizeAllCommentsBranch(this); return false;" ';
		}
		echo '
		<a name="comment"></a>
			<div class="commentsBlock"  attrIdCommentsBlock="comments_block_' . $idEssence . '" attrURL="' . $url . '">
				<div class="coments_text_box">
					<a name="comments"></a>
					<span class="svernut_all">
						<a href="#"' . $onClickBranch . 'class="minimizeAllCommentsBranch" attr_id_essence="' . $idEssence . '">' . $branchMinimizeAllCommentText . '</a>
					</span>
					<ul>';
				if ($type != 'question'){
					echo '<li><a href="/" onclick="' . $onClick . '" class="showOrHideComments jsHref" attrIdSlideLink="link_' . $idEssence . '">Комментарии</a></li>';
				}else {
					echo '<li><strong style="font-size:16px;">Ответы (<span id="answersAmount">' . $arrForAnswer['answerCount'] . '</span>)</strong></li>';
				}
		if ($viewLinkToAddRootComment)
			self::viewLinkToAddRootComment($textLink, $type, $idEssence, false, $isLinear, $pollFlag, $idFolder, 1);
		echo '
				</ul>
				</div>
				<div ' . $style . ' class="commentsOneSlideLink" attrIdCommentsOneSlideLink="block_' . $idEssence . '">

						<form style="display: none;" attrDraft="yes" attrId="comment_add_' . $idEssence . '" method="POST"><textarea style="width: 500px;" rows="5" class="" attrOneWindow="none" attrW="notW" name="text"></textarea>
							<input type="image" src="' . W_IMAGES . 'button/btn_ostavut_comemt.gif" name="submitComment" value="Ответить" class="submitComment"/><input type="image" src="' . W_IMAGES . 'button/btn_zakrut.gif" href="#" id="" name="closeForm" value="закрыть"/>
						</form>';
		echo View_Comment::viewCurComments($arrComments, $idEssence, $type, $arrUserInfo, $isLinear, $pollFlag, $branchMinimizeFlag, '', $idFolder, false, $arrForAnswer, $url);
		echo '

				</div>
			';
		if ($viewLinkToAddRootComment){
			!sizeof($arrComments) ? $style = 'display:none;' : $style = '';
			echo '<div class="coments_text_box" style="border-bottom:none; ' . $style . '" id="coments_text_box_root_2">
						<ul>
						';
			self::viewLinkToAddRootComment($textLink, $type, $idEssence, false, $isLinear, $pollFlag, $idFolder, 2);
			echo '</ul>';
			echo '</div>';
		}

		echo '</div>';
	}

	/**
	 * отображения списка комментариев пользователя
	 */
	public static function viewUsersComments($arrComments, $arrUser) {
	  echo '<div id="userComments">';
  		foreach ($arrComments as $arrComment){
  			echo '
  			<div class="comment_text"><div class="comments_author">
  			  <div class="rigt_rating_box">
  			  ' . View_Poll::showAverageMark(Poll::calculateMark($arrComment['marks_minus'], $arrComment['marks_plus']), $arrComment['marks_minus'], $arrComment['marks_plus']) . '
  			  	 </div>
  			  	 	 <a class="author_link" href="' . W_ABSPATH . 'user/' .  $arrComment['author_login'] . '">
  			  	 <img src="' . W_ABSPATH . 'content/images/pictures/user/vs_' . (isset($arrComment['pic_path']) ? ($arrComment['ID_author'] . '.' . $arrComment['pic_path']) : 'default.gif') . '" class="user"/>
  			  	 </a>
  								<ul class="name_autor">
  								<li>';
  			if ($arrComment['essence_type'] != 11 && $arrComment['essence_type'] != 17 ) {
  				echo '<a href="' . W_ABSPATH . Service_Essence::getEssenceTypeName($arrComment['essence_type']) . 's?' . ($arrComment['essence_type'] == 5 ? 'folder' : 'idFolder') . '=' . $arrComment['ID_folder'] . '">' . $arrComment['folder_name'] . '</a> / ';
  			}
  			/*if ($arrComment['essence_type'] == 17) $essenceUrl = 'bug/' . $arrComment['ID_essence'];
  			else */
  			$essenceUrl = Service_Essence::getEssenceUrl($arrComment['essence_type'], $arrComment['ID_essence']);
  
  			echo ' <a href="' . W_ABSPATH . $essenceUrl . ($arrComment['essence_type'] != 11 ? '#comment' . $arrComment['ID_comment'] : '#comments') . '">
  					    					' . $arrComment['essence_name'] . '
  					    				</a>
  					    			</li>
  					    			<li>
  					    				' . Service_Date::getCaseDateForUser($arrComment['creation']) . '
  					    			</li>
  		    			  </ul>
  		  	  </div><p class="commentText">' . $arrComment['text'] . '</p>
  				</div><br/>';
  		}
		echo '</div>';
	}

	/**
	 * функция для отображения на экране ссылки на выставление корневого комментария
	 *
	 * @param string $textLink - текст ссылки
	 * @param string $type - name сущности( тип ), к котрой ставится комментарий
	 * @param int $idEssence - id сущности, к котрой ставится комментарий
	 */
	public static function viewLinkToAddRootComment($textLink, $type, $idEssence, $hideAtStart = false, $isLinear = false, $pollFlag = true, $idFolder = 0, $number = 1){
		$objSession = User_Session::instance();
		if ($isLinear)
			$isLinear = 1;
		else $isLinear = 0;
		if ($pollFlag)
			$pollFlag = 1;
		else $pollFlag = 0;
		if ($objSession->isLoggedIn()){
			$id = $type . '_' . $idEssence . '_root_' . $number;
			$url = W_ABSPATH . 'content/pages/comment/addComment.php?curEssenceId=' . $idEssence . '&type=' . $type;
			$onClick = 'comment.showFormForAnswer(\'' . $id . '\', ' . $idEssence . ', \'' . $type . '\', 0, \'NULL\', ' . $isLinear . ', ' . $pollFlag . ', ' . $idFolder . ');return false;';
			echo '

			    <li style="' . ($hideAtStart ? 'dispaly:none;' : '') . '"><a attrIdanswerLink="' . $id . '" href="' . $url . '" class="answerLink jsHref" onClick="' . $onClick . '" attrIdEssence="'.$idEssence.'" attrEssenceType="'.$type.'" >' .  $textLink . '</a></li>
			    				<div id="' . $id . '">
				</div>';
		}
	}

	public static function showLifeDilogue($LiveDialogue){
		echo '<div class="main_page_content_bottom">';
			echo '<h2><a class="black" href="' . W_ABSPATH . 'liveDialogue">Последние комментарии</a></h2>';

			echo '<div class="main_page_bottom_box">';
				echo '<h3><a class="blackNone" href="' . W_ABSPATH . 'articles?idFolder=1">Веб-программирование</a></h3>';
				View_Comment::showLifeDilogueIndex($LiveDialogue[0]);
			echo '</div>';

			echo '<div class="main_page_bottom_box">';
				echo '<h3><a class="blackNone" href="' . W_ABSPATH . 'articles?idFolder=2">Десктопное программирование</a></h3>';
				View_Comment::showLifeDilogueIndex($LiveDialogue[1]);
			echo '</div>';

			echo '<div class="main_page_bottom_box main_page_bottom_box_last">';
				echo '<h3><a class="blackNone" href="' . W_ABSPATH . 'articles?idFolder=3">Базы данных</a></h3>';
				View_Comment::showLifeDilogueIndex($LiveDialogue[2]);
			echo '</div>';
		echo '</div>';
	}

	/**
	 * Последние комментарии на главной
	 *
	 */
	public static function showLifeDilogueIndex($LiveDialogue){
		foreach ($LiveDialogue as $arr){
			if (isset($arr['ID_article'])){
				echo '
				<ul class="crumbs">
					<li><a href="' . W_ABSPATH . 'articles?idFolder=' . $arr['ID_folder'] . '">' . $arr['folder_name'] . '</a></li>
					<li class="last"><a href="' . W_ABSPATH . 'article/' . $arr['ID_article'] . '">' . $arr['article_name'] . '</a></li>
				</ul>
				<span class="bottom_info"><a href="' . W_ABSPATH . 'user/' . $arr['login'] . '">' . $arr['login'] . '</a>, всего <a href="' . W_ABSPATH . 'article/' . $arr['ID_article'] . '/#comments" class="color_namber">' . $arr['comment_amount'] . Service_Declension::getCommentsDeclension($arr['comment_amount']) . '</a></span>';
			}
			elseif (isset($arr['ID_tutorial_lesson'])){
				echo '
				<ul class="crumbs">
					<li><a href="' . W_ABSPATH . 'tutorials?idFolder=' . $arr['ID_folder'] . '">' . $arr['folder_name'] . '</a></li>
					<li class="last"><a href="' . W_ABSPATH . 'tutorial/' . $arr['url_name'] . '/lesson/' . $arr['ID_tutorial_lesson'] . '">' . $arr['lesson_name'] . '</a></li>
				</ul>
				<span class="bottom_info"><a href="' . W_ABSPATH . 'user/' . $arr['login'] . '">' . $arr['login'] . '</a>, всего <a href="' . W_ABSPATH . 'tutorial/' . $arr['url_name'] . '/lesson/' . $arr['ID_tutorial_lesson'] . '/#comments" class="color_namber">' . $arr['comment_amount'] . Service_Declension::getCommentsDeclension($arr['comment_amount']) . '</a></span>';
			}
		}
	}
}
?>